package cn.sylinx.horm.example.section13;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import cn.sylinx.horm.type.JdbcType;
import cn.sylinx.horm.type.JdbcTypeMapper;
import cn.sylinx.horm.type.handler.BaseTypeHandler;

@SuppressWarnings("unchecked")
public class JSONTypeHandler extends BaseTypeHandler<Map<String, Object>> {

    @Override
    protected JdbcTypeMapper getJdbcTypeMapper() {
        return JdbcType.VARCHAR;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, Object> parameter) throws SQLException {
        String json = JSONUtil.toJsonStr(parameter);
        ps.setString(i, json);
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json == null) {
            return null;
        }
        return JSONUtil.parse(json).toBean(Map.class);
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        if (json == null) {
            return null;
        }
        return JSONUtil.parse(json).toBean(Map.class);
    }

    @Override
    public Map<String, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        if (json == null) {
            return null;
        }
        return JSONUtil.parse(json).toBean(Map.class);
    }
}
